# -*- coding: utf-8 -*-
import oss2
import os

auth = oss2.Auth('LTAI4FyhUYxyN7ncBpwf2a81', 'qLvXqsVUYWSQGZVto12oVNjoO8lNLr')
bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', 'mshare-plusnew')

root_path = 'dist'


def upload_file(upload_path, file_path):
    file_name = os.path.basename(file_path).split(".")[0]
    file_suffix = os.path.splitext(file_path)[-1]
    print('upload_file,file_name:' + file_name + ',file_suffix:' + file_suffix)
    if file_name == "":
        return
    headers = None
    if file_suffix == '.js':
        headers = {'Content-Type': 'application/javascript'}
    bucket.put_object_from_file(upload_path.replace("\\","/"), file_path, headers=headers)


def clear_bucket():
    for obj in oss2.ObjectIterator(bucket, delimiter='/'):
        # 通过is_prefix方法判断obj是否为文件夹。
        if obj.is_prefix():  # 文件夹
            for child2 in oss2.ObjectIterator(bucket, prefix=obj.key):
                print('child2: ' + child2.key)
                bucket.delete_object(child2.key)
        else:  # 文件
            print('file: ' + obj.key)
            bucket.delete_object(obj.key)


def upload_all_files(root_path):
    for root, dirs, files in os.walk(root_path):
        for name in files:
            file_path = os.path.join(root, name)
            upload_path = file_path[len(root_path) + 1:len(file_path)]
            print(file_path)
            print(upload_path)
            upload_file(upload_path, file_path)


clear_bucket()

upload_all_files(root_path)
